import json
import smtplib
import requests
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from wcferry import Wcf, WxMsg
from threading import Thread

# 初始化 Wcf 实例
wcf = Wcf()

# API 处理函数
API_URL = "https://api.example.com/v1/process"  # 替换为实际API地址


def call_api(action, target, content):
    """
    调用 API 以处理邮件发送逻辑
    :param action: 动作（例如 "发送邮件"）
    :param target: 目标邮箱地址
    :param content: 邮件内容
    :return: API 返回的 JSON 数据
    """
    payload = {
        "动作": action,
        "目标": target,
        "内容": content
    }
    headers = {"Content-Type": "application/json"}

    response = requests.post(API_URL, json=payload, headers=headers)
    return response.json() if response.status_code == 200 else {}


# 发送邮件功能
def send_email(to_email, subject, body):
    """
    通过 QQ 邮箱 SMTP 发送邮件
    :param to_email: 收件人邮箱
    :param subject: 邮件主题
    :param body: 邮件正文
    """
    sender_email = "your_qq_email@qq.com"  # 替换为你的QQ邮箱
    sender_password = "your_smtp_password"  # 需要申请QQ邮箱授权码
    smtp_server = "smtp.qq.com"

    msg = MIMEMultipart()
    msg["From"] = sender_email
    msg["To"] = to_email
    msg["Subject"] = subject

    msg.attach(MIMEText(body, "plain"))

    try:
        server = smtplib.SMTP_SSL(smtp_server, 465)
        server.login(sender_email, sender_password)
        server.sendmail(sender_email, to_email, msg.as_string())
        server.quit()
        print("邮件发送成功")
        return True
    except Exception as e:
        print(f"邮件发送失败: {e}")
        return False


# 自动润色信息，调用 GPT API
def gpt_request(messages):
    """
    调用 GPT API 接口进行消息回复，自动润色提示信息
    :param messages: 历史消息列表
    :return: GPT 回复消息
    """
    if not messages:
        return "没有可用的用户消息"

    final_text = (
            "请你模仿一个计算机专业的低调大学生zp，请你简单回答他的同学提问的问题 "
            + "当前问题: " + messages[0]  # 当前问题
            + " 历史交流信息: " + " ".join(messages[1:])  # 历史信息
    )

    payload = {
        "model": "gpt-4o-mini",
        "messages": [{"role": "user", "content": final_text}],
    }

    headers = {
        "Authorization": "Bearer YOUR_API_KEY",  # 替换为实际的 API Token
        "Content-Type": "application/json",
    }

    url = "https://api.example.com/v1/chat/completions"

    try:
        response = requests.post(url, headers=headers, json=payload, timeout=30)
        response.raise_for_status()
        data = response.json()
        return data["choices"][0]["message"]["content"]
    except Exception as e:
        print(f"调用GPT接口时出错: {e}")
        return "接口开发中(异常)"


# 处理用户消息
def process_message(msg):
    """
    处理用户发送的消息，并根据逻辑补全信息
    :param msg: 微信消息对象
    """
    content = msg.content.strip()
    sender = msg.sender  # 可能是 wxid 或 roomid

    # 检查是否为 /zp 指令
    if content.startswith("/zp"):
        parts = content.split("我要发送的内容是")

        if len(parts) == 1:
            # 第一次触发，仅有 "/zp"，调用 API 检查是否缺少信息
            api_response = call_api("发送邮件", "3026418933@qq.com", "")

            if api_response.get("动作") == "发送邮件" and api_response.get(
                    "目标") == "3026418933@qq.com" and not api_response.get("内容"):
                wcf.send_text("想要发送什么内容呢？", sender)

        elif len(parts) == 2:
            # 用户输入 "/zp 我要发送的内容是xxx"
            email_content = parts[1].strip()

            # 调用 API 补全 JSON 格式的元素
            api_response = call_api("发送邮件", "3026418933@qq.com", email_content)

            # 检查是否缺少其他元素
            if api_response.get("动作") == "发送邮件":
                missing_elements = []

                # 检查目标元素
                if not api_response.get("目标"):
                    missing_elements.append("目标")

                # 检查内容元素
                if not api_response.get("内容"):
                    missing_elements.append("内容")

                if missing_elements:
                    # 使用 GPT 进行自动润色并提示用户补充缺失的元素
                    missing_msg = "请补全以下缺少的信息: " + ", ".join(missing_elements)
                    refined_message = gpt_request([missing_msg])
                    wcf.send_text(refined_message, sender)
                else:
                    # 所有元素完整，执行发送邮件
                    success = send_email("3026418933@qq.com", "自动发送邮件", email_content)
                    if success:
                        wcf.send_text("邮件已成功发送！", sender)
                    else:
                        wcf.send_text("邮件发送失败，请稍后重试。", sender)


# 启动消息监听
def receive_message():
    """
    启动消息监听，获取并处理消息
    """

    def listen_messages():
        while wcf.is_receiving_msg():
            try:
                msg = wcf.get_msg()
                process_message(msg)
            except Exception as e:
                print(f"消息处理出错: {e}")

    print("启动消息监听...")
    wcf.enable_receiving_msg()
    Thread(target=listen_messages, name="ListenMessageThread", daemon=True).start()


# 启动监听
if __name__ == "__main__":
    receive_message()
